/*
 * inireader.c
 *
 *  Created on: 2012-3-20
 *      Author: chao
 */

#include "inireader.h"
#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "conf.h"

int str2int(char s[]) {
	int res = 0;
	int i = 0;
	for (; s[i] != '\0'; ++i) {
		res *= 10;
		res += s[i] - '0';
	}
	return res;
}

void iniParser(char s[]) {
	if (s[0] == ' ' || s[0] == '#' || s[0] == '[')
		return;
	char *name, *value;
	name = (char*) malloc(100);
	value = (char*) malloc(100);
	int i = 0;
	for (; s[i] != '\0' && s[i] != '='; ++i) {
		name[i] = s[i];
	}
	name[i] = '\0';
	int j = 0;

	if (s[i + 1] == '\0') {
		free(name);
		free(value);
		return;
	} else {
		++i;
	}
	for (; s[i] != '\0'; ++i, ++j) {
		value[j] = s[i];
	}
	value[j] = '\0';
	systemLogger(name);
	systemLogger(value);

	if (strcmp(name, "ip_port") == 0) {
		if (strlen(value) != 0) {
			strcpy(IP_PORT, value);

		}
	} else if (strcmp(name, "MAXRAM") == 0) {
		int maxram = str2int(value);
		if (maxram > 0) {
			MAX_RAM_USED = maxram;
		}
	} else if (strcmp(name, "STROAGE") == 0) {
		int stroagetype = str2int(value);
		STORAGE_TYPE = stroagetype;
	}
	free(name);
	free(value);
}

void iniInit() {
	FILE* f = fopen("config.ini", "r");
	if(f==NULL){
		systemLogger("Cannot find config.ini, ChaosDB run as default.");
		return;
	}
	char s[100];

	while (fgets(s, 100, f) != NULL) {
		iniParser(s);
	}
	fclose(f);
}

